package com.mock.ai.repository;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.mock.ai.entity.po.ConversationInfo;
import com.mock.ai.service.IConversationInfoService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.vectorstore.elasticsearch.ElasticsearchVectorStore;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Component;

import java.io.*;
import java.nio.file.Files;
import java.util.Objects;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
@Component
@RequiredArgsConstructor
public class LocalPdfFileRepository implements FileRepository {

//    private final ElasticsearchVectorStore vectorStore;

    // 会话id 与 文件名的对应关系，方便查询会话历史时重新加载文件
    private final Properties chatFiles = new Properties();

    private final IConversationInfoService conversationInfoService;

    private static final ConcurrentHashMap<String, String> CHAT_FILES = new ConcurrentHashMap<>();

    @Override
    public boolean save(String chatId, Resource resource) {
        // 1.保存到本地磁盘
        String filename = chatId + resource.getFilename();
        File target = new File(Objects.requireNonNull(filename));
        if (!target.exists()) {
            try {
                Files.copy(resource.getInputStream(), target.toPath());
            } catch (IOException e) {
                log.error("Failed to save PDF resource.", e);
                return false;
            }
        }

        // 2.保存映射关系
        ConversationInfo conversationInfo = new ConversationInfo();
        conversationInfo.setConversationId(chatId);
        conversationInfo.setType("pdf");
        conversationInfo.setPdfPath(filename);
        conversationInfoService.save(conversationInfo);
        return true;
    }

    @Override
    public Resource getFile(String chatId) {
        log.info("Get file for chatId: {}", CHAT_FILES.get(chatId));
        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("conversation_id", chatId);
        ConversationInfo conversationInfo = conversationInfoService.getOne(queryWrapper);
        return new FileSystemResource(conversationInfo.getPdfPath());
    }

//    @PostConstruct
//    private void init() {
//        FileSystemResource pdfResource = new FileSystemResource("chat-pdf.properties");
//        if (pdfResource.exists()) {
//            try {
//                chatFiles.load(new BufferedReader(new InputStreamReader(pdfResource.getInputStream(), StandardCharsets.UTF_8)));
//            } catch (IOException e) {
//                throw new RuntimeException(e);
//            }
//        }
//        FileSystemResource vectorResource = new FileSystemResource("chat-pdf.json");
//        if (vectorResource.exists()) {
//
//            vectorStore.;
//        }
//    }
//
//    @PreDestroy
//    private void persistent() {
//        try {
//            chatFiles.store(new FileWriter("chat-pdf.properties"), LocalDateTime.now().toString());
//            SimpleVectorStore simpleVectorStore = (SimpleVectorStore) vectorStore;
//            simpleVectorStore.save(new File("chat-pdf.json"));
//        } catch (IOException e) {
//            throw new RuntimeException(e);
//        }
//    }
}